# -*- coding: utf-8 -*-
import logging
from config import config
from utils.mysql_util import MysqlUtil


class MysqlSelect:

    def __init__(self):
        """
        调用数据库查询方法
        :param table: 表名
        :param where: 判断条件（不写默认查询整个表）
        :param param: 你所要获取到字段的条件
        """
        info = config.Config()
        mysql_host = info.mysql_host
        mysql_port = info.mysql_port
        mysql_user = info.mysql_user
        mysql_password = info.mysql_password
        mysql_database = info.mysql_database
        self.db = MysqlUtil(host=mysql_host, port=mysql_port, user=mysql_user, password=mysql_password,
                            db=mysql_database)

    def mysql_select_first(self, table, key_data=None, value_data=None, param=None):
        """
        查找单条数据, 获取对应的字段的值
        :param table: 表名
        :param key_data: 判断的字段名用[]传入，[字段1,字段2,字段3]
        :param value_data: 判断的字段值用[]传入，[值1,值2,值3]
        :param param: 你所要获取到字段的条件
        :return: 返回值是对应字段的值
        """
        if not key_data and not value_data:
            where = None
        else:
            where = {}
            for key, value in zip(key_data, value_data):
                where[key] = value

        data = self.db.table(table).where(where).find()
        if len(data) == 1:
            if param:
                value = data[0][param]
            else:
                value = data[0]
            self.close_mysql()
            return value
        elif len(data) > 1:
            raise Exception(f"获取到的数据不为1，数据条数为：{len(data)}，数据内容为：{data}")
        elif len(data) == 0:
            logging.error(f"未匹配到数据，不满足条件：{where}")
            raise Exception(f"未匹配到对应的数据，实际结果：{data}")
        self.close_mysql()

    def mysql_length(self, table, key_data=None, value_data=None):
        """
        获取到符合条件数据的数量
        :param table: 表名
        :param key_data: 判断的字段名用[]传入，[字段1,字段2,字段3]
        :param value_data: 判断的字段值用[]传入，[值1,值2,值3]
        :return: 返回值是数据的数量
        """
        if not key_data and not value_data:
            where = None
        else:
            where = {}
            for key, value in zip(key_data, value_data):
                where[key] = value

        data = self.db.table(table).where(where).find()
        self.close_mysql()
        return len(data)

    def close_mysql(self):
        self.db.close()


if __name__ == '__main__':
    password = MysqlSelect().mysql_select_first('y_user', ["username"], ["admin"], 'pwd')
    print(password)
